package org.csu.springjpetstore.service;

import org.csu.springjpetstore.domain.Account;
import org.csu.springjpetstore.persistence.AccountMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class AccountService1 {
    @Autowired
    private AccountMapper accountMapper;


    public Account getAccount(String username) {
        return accountMapper.getAccountByUsername(username);
    }

    public Account getAccount(String username, String password) {
        Account account = new Account();
        account.setUsername(username);
        account.setPassword(password);
        return accountMapper.getAccountByUsernameAndPassword(account);
    }


    @Transactional
    public void insertAccount(Account account) {
        accountMapper.insertAccount(account);
        accountMapper.insertProfile(account);
        accountMapper.insertSignon(account);
    }

    @Transactional
    public void updateAccount(Account account) {
        accountMapper.updateAccount(account);
        accountMapper.updateProfile(account);

        if (account.getPassword() != null && account.getPassword().length() > 0) {
            accountMapper.updateSignon(account);
        }
    }

    public Account login(String username, String password) {
        Account account = new Account();
        account.setUsername(username);
        account.setPassword(password);
        return accountMapper.getAccountByUsernameAndPassword(account);
    }

    public int register(Account user) {
        if (user == null) {
            return 0;
        }
        if (isUsernameExist(user.getUsername())) {
            //用户名已存在，不能注册
            return -1;
        } else {
            accountMapper.insertAccount(user);
            accountMapper.insertProfile(user);
            accountMapper.insertSignon(user);
            return 1;
        }
    }

    public int editAccountIncludeUsername(Account user, String currentUsername) {
        Account account = new Account();
        account.setUsername(currentUsername);
        if (isUsernameExist(user.getUsername())) {
            //新用户名存在
            if (user.getUsername().equals(currentUsername)) {
                //是自己的用户名
                accountMapper.updateAccount(user);
                accountMapper.updateProfile(user);
                accountMapper.updateSignon(user);
                return 1;
            }
            //不是自己的用户名
            //新用户名已被占用
            return -1;
        }
        //新用户名不存在
        accountMapper.updateAccount(user);
        accountMapper.updateProfile(user);
        accountMapper.updateSignon(user);
        return 1;
    }

    public boolean isUsernameExist(String username) {
        Account account = accountMapper.getAccountByUsername(username);
        if (account == null)
            return false;
        else return true;
    }
}
